import request from '@/utils/request'

// 合同类型定义
export interface Contract {
  id: string
  contractName: string
  contractNo: string
  tenantId: string
  tenantName: string
  amount: number
  status: 'draft' | 'pending' | 'approved' | 'rejected' | 'expired'
  uploaderId: string
  uploaderName: string
  approvalId?: string
  approvalName?: string
  approvalTime?: string
  approvalComment?: string
  startDate: string
  endDate: string
  fileUrl: string
  fileName: string
  createdAt: string
  updatedAt: string
}

// 合同查询参数
export interface ContractQuery {
  page?: number
  pageSize?: number
  keyword?: string
  status?: Contract['status']
  tenantId?: string
  startDate?: string
  endDate?: string
}

// 创建合同
export const createContract = (
  contractData: Omit<
    Contract,
    | 'id'
    | 'createdAt'
    | 'updatedAt'
    | 'tenantName'
    | 'uploaderName'
    | 'approvalName'
    | 'approvalTime'
  >,
) => {
  return request.post<Contract>('/contracts', contractData)
}

// 获取合同列表
export const getContracts = (query?: ContractQuery) => {
  return request.get<{ list: Contract[]; total: number }>('/contracts', { params: query })
}

// 获取单个合同
export const getContract = (id: string) => {
  return request.get<Contract>(`/contracts/${id}`)
}

// 更新合同
export const updateContract = (
  id: string,
  contractData: Partial<
    Omit<
      Contract,
      | 'id'
      | 'createdAt'
      | 'updatedAt'
      | 'tenantName'
      | 'uploaderName'
      | 'approvalName'
      | 'approvalTime'
    >
  >,
) => {
  return request.put<Contract>(`/contracts/${id}`, contractData)
}

// 删除合同
export const deleteContract = (id: string) => {
  return request.delete(`/contracts/${id}`)
}

// 批量删除合同
export const batchDeleteContracts = (ids: string[]) => {
  return request.delete('/contracts/batch', { data: { ids } })
}

// 上传合同文件
export const uploadContractFile = (file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  return request.post<{ fileUrl: string; fileName: string }>('/contracts/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
    },
  })
}

// 审批合同
export const approveContract = (id: string, data: { comment?: string }) => {
  return request.post<Contract>(`/contracts/${id}/approve`, data)
}

// 拒绝合同
export const rejectContract = (id: string, data: { comment: string }) => {
  return request.post<Contract>(`/contracts/${id}/reject`, data)
}

// 获取合同状态统计
export const getContractStats = () => {
  return request.get<{
    draft: number
    pending: number
    approved: number
    rejected: number
    expired: number
  }>('/contracts/stats')
}
